<template>
  <div class="dashboard-container">
    <!-- 新增欢迎头部 -->
    <welcome-header/>
    <!-- 统计卡片区 -->
    <el-row :gutter="20" class="mb-20">
      <el-col
        v-for="item in statData"
        :key="item.title"
        :xs="24"
        :sm="12"
        :lg="6"
      >
        <stat-card
          :title="item.title"
          :value="item.value"
          :icon="item.icon"
          :color="item.color"
        />
      </el-col>
    </el-row>

    <!-- 图表区 -->
    <el-row :gutter="20" class="mb-20" v-if="false">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>业务数据趋势</span>
            <el-radio-group
              v-model="chartType"
              size="small"
              style="float: right"
            >
              <el-radio-button label="line">折线图</el-radio-button>
              <el-radio-button label="bar">柱状图</el-radio-button>
            </el-radio-group>
          </div>
          <chart
            :type="chartType"
            :data="chartData"
            height="400px"
            @chart-click="handleChartClick"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格区 -->
    <el-card shadow="hover">
      <div slot="header" class="table-header">
        <div class="table-title">画课记录</div>
        <div class="table-actions" v-show="isQuery">
          <el-form :inline="true" :model="queryParams" class="compact-form">
            <el-form-item label="归属科室" prop="deptId" v-if="!isDoctor && !isPatient">
              <treeselect v-model="queryParams.deptId" :options="enabledDeptOptions" :show-count="true"
                          style="width: 120px;" placeholder="请选择归属科室"/>
            </el-form-item>
            <el-form-item label="医生" prop="doctorName" v-if="!isDoctor">
              <el-input
                v-model="queryParams.doctorName"
                placeholder="请输入医生"
                clearable
                style="width: 120px;"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="患者" prop="patientName" v-if="!isPatient">
              <el-input
                v-model="queryParams.patientName"
                placeholder="请输入患者"
                clearable
                style="width: 120px;"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="画课月份" prop="courseDate">
              <el-date-picker v-model="courseMonth" style="width: 120px" placeholder="选择月份" type="month" ></el-date-picker>
            </el-form-item>
<!--            <el-form-item label="画课日期" prop="courseDate">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                              range-separator="-" start-placeholder="开始日期"
                              end-placeholder="结束日期"></el-date-picker>
            </el-form-item>-->
            <el-form-item label="画课项目" prop="courseProject">
              <el-select v-model="queryParams.courseProject" placeholder="画课项目" style="width: 120px;" clearable>
                <el-option
                  v-for="dict in dict.type.sys_course_project"
                  :key="dict.label"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="画课状态" prop="courseStatus">
              <el-select v-model="queryParams.courseStatus" placeholder="请选择" style="width: 120px;" clearable>
                <el-option
                  v-for="item in courseStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- 操作按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              >搜索
              </el-button>
              <el-button
                icon="el-icon-refresh"
                size="small"
                @click="resetQuery"
              >重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-button
          type="primary"
          icon="el-icon-s-operation"
          size="small"
          @click="handleShowQuery"
        >{{ isQueryText }}
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
        :data="tableData"
        :height="tableHeight"
        ref="summaryTable"
      >
        <el-table-column label="序号" type="index" width="55" align="center">
          <template slot-scope="scope">
            <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医生姓名" align="center" prop="doctorName"/>
        <el-table-column label="患者姓名" align="center" prop="patientName"/>
        <el-table-column label="院区名称" align="center" prop="parentName" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.dept.parentName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="科室名称" align="center" prop="deptName" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.dept.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="画课日期" align="center" prop="courseDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="画课项目" align="center" prop="courseProject"/>
        <el-table-column label="画课时长" align="center" prop="courseHour">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_course_hour" :value="scope.row.courseHour"/>
          </template>
        </el-table-column>
        <el-table-column label="画课状态" prop="courseStatus">
          <template v-slot="scope">
            <span v-if="scope.row.courseStatus == 1" style="color: orange">待确认</span>
            <span v-if="scope.row.courseStatus == 2" style="color: green">患者确认</span>
            <span v-if="scope.row.courseStatus == 3" style="color: green">自动确认</span>
          </template>
        </el-table-column>
        <el-table-column label="确认时间" align="center" prop="confirmTime" width="170">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.confirmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script>
import {getUserProfile} from "@/api/system/user"
import {listCourse} from "@/api/yushi/course"
import {getStatistics, getChartData} from "@/api/dashboard";
import StatCard from '@/views/dashboard/components/StatCard'
import Chart from '@/views/dashboard/components/Chart'
import WelcomeHeader from '@/views/dashboard/components/WelcomeHeader'
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {Splitpanes, Pane} from "splitpanes"
import "splitpanes/dist/splitpanes.css"

export default {
  name: "Dashboard",
  components: {Treeselect, Splitpanes, Pane, WelcomeHeader, StatCard, Chart},
  dicts: ['sys_course_hour', 'sys_course_project'],
  data() {
    return {
      tableHeight: '',//表格高度
      user: {},
      isDoctor: false,
      isPatient: false,
      // 统计数据
      statData: [
        {title: '医生数量', value: 0, icon: 'el-icon-user', color: '#67C23A'},
        {title: '患者数量', value: 0, icon: 'el-icon-shopping-cart-2', color: '#409EFF'},
        {title: '今日总课时', value: 0, icon: 'el-icon-document', color: '#E6A23C'},
        {title: '当月总课时', value: 0, icon: 'el-icon-bell', color: '#F56C6C'}
      ],

      // 图表配置
      chartType: 'line',
      chartData: {
        xAxis: [],
        series: []
      },
      //画课确认状态
      courseStatusOptions: [
        {value: 1, label: '待确认'},
        {value: 2, label: '患者确认'},
      ],
      isQuery: false,
      isQueryText: '展开查询',
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 日期范围
      dateRange: [],
      resizeObserver: null,
      courseMonth:'',
    }
  },
  created() {
    // this.getChartData()
    this.getUser()
    this.getStatisticsData()
    this.getList()
    this.getTableHeight()
  },
  mounted() {
    //挂载window.onresize事件(动态设置table高度)
    const _this = this;
    window.onresize = () => {
      if (_this.resizeFlag) {
        clearTimeout(_this.resizeFlag);
      }
      _this.resizeFlag = setTimeout(() => {
        _this.getTableHeight();
        _this.resizeFlag = null;
      }, 100);
    };
    _this.getTableHeight()
    _this.initResizeObserver();
  },
  beforeDestroy() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  },
  methods: {
    // 初始化ResizeObserver
    initResizeObserver() {
      if (typeof ResizeObserver !== 'undefined' && this.$refs.tableWrapper) {
        this.resizeObserver = new ResizeObserver(() => {
          this.updateTableLayout();
        });
        this.resizeObserver.observe(this.$refs.tableWrapper);
      }
    },

    // 更新表格布局
    updateTableLayout() {
      if (this.$refs.summaryTable && this.$refs.summaryTable.doLayout) {
        setTimeout(() => {
          this.$refs.summaryTable.doLayout();
        }, 100);
      }
    },

    //计算table高度(动态设置table高度)
    getTableHeight() {
      const innerHeight = window.innerHeight
      //距离页面下方的高度
      let tableH = 508;
      let tableHeightDetil = innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        this.tableHeight = 300;
      } else {
        this.tableHeight = window.innerHeight - tableH;
      }
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        let roleKeys = response.data.roles.map(role => role.roleKey).join(',');
        if (roleKeys.includes('patient') > 0) {
          this.isPatient = true
        }
        if (roleKeys.includes('doctor') > 0) {
          this.isDoctor = true
        }
        //既不是医生也不是患者
        if (!this.isDoctor && !this.isPatient) {
          this.getDeptTree()
        }
      })
    },
    // 获取统计数据
    getStatisticsData() {
      this.queryParams.courseMonth = this.parseTime(this.courseMonth, '{y}-{m}')
      getStatistics(this.queryParams).then(response => {
        this.statData.forEach(item => {
          item.value = response.data[item.title] || 0
        })
      })
    },

    // 获取图表数据
    getChartData() {
      getChartData().then(response => {
        this.chartData = {
          xAxis: response.data.months,
          series: response.data.values
        }
      })
    },
    handleShowQuery() {
      if (this.isQuery) {
        this.isQuery = false
        this.isQueryText = '展开'
      } else {
        this.isQuery = true
        this.isQueryText = '收起'
      }
    },
    handleQuery() {
      this.getList()
      this.getStatisticsData()
    },
    resetQuery() {
      this.courseMonth = ''
      this.dateRange = []
      this.queryParams = {}
      this.handleQuery()
    },
    // 获取表格数据
    getList() {
      this.loading = true
      let params = this.addDateRange(this.queryParams, this.dateRange)
      params.courseMonth = this.parseTime(this.courseMonth, '{y}-{m}')
      listCourse(params).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
      })
      this.getTableHeight()
    },

    // 图表点击事件
    handleChartClick(params) {
      this.queryParams.beginTime = params.name + '-01'
      this.queryParams.endTime = params.name + '-31'
      this.getList()
    },

    // 表格排序
    handleSortChange(column) {
      this.queryParams.orderByColumn = column.prop
      this.queryParams.isAsc = column.order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },

    // 刷新数据
    refreshList() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 导出数据
    exportData() {
      this.download('/monitor/operlog/export', {
        ...this.queryParams
      }, `操作日志_${new Date().getTime()}.xlsx`)
    },

    // 操作类型标签样式
    getOperationTypeTag(type) {
      const typeMap = {
        '1': '',    // 新增
        '2': 'success', // 修改
        '3': 'danger',  // 删除
        '4': 'info',    // 授权
        '5': 'warning'  // 导出
      }
      return typeMap[type] || ''
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },

  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.mb-20 {
  margin-bottom: 10px;
}

.el-card {
  margin-bottom: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

/* 表单行间距调整 */
.demo-form-inline {
  margin-bottom: -18px;
}

/* 表单元素间距 */
.el-form-item {
  margin-right: 15px;
  margin-bottom: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .el-select, .el-input, .el-date-editor {
    width: 100% !important;
  }
}
</style>

<style scoped>
/* 表格头部布局 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 !important;
  height: 56px;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  padding-left: 20px;
}

.table-actions {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

/* 紧凑型表单 */
.compact-form {
  margin-bottom: 0;
}

.compact-form >>> .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    height: auto;
    padding: 10px 0 !important;
  }

  .table-title {
    width: 100%;
    padding: 0 0 10px 0;
    text-align: center;
  }

  .table-actions {
    width: 100%;
    justify-content: center;
  }

  .compact-form >>> .el-form-item {
    margin-right: 5px;
    margin-bottom: 5px;
  }
}
</style>
